package com.tmsps.ne4weixin.utils;

import java.io.PrintWriter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tmsps.ne4weixin.config.WxConfig;

/**
 * @Title: WXUtil.java
 * @Package com.tmsps.ne4weixin.utils
 * @Description: 微信公众号小工具
 * @author: zhangwei
 * @date: 2019-09-20
 * @version v1.0
 * @Copyright: 2019 nuoyun All rights reserved.
 */
public class WXUtil {
	protected static Logger log = LoggerFactory.getLogger(WXUtil.class);
	
	/**
	 * 验证服务器地址(URL)		
	 * @param request
	 * @param response
	 * @param token		令牌(Token)
	 */
	public static void checkServer(HttpServletRequest request,HttpServletResponse response, String token) {
		String echostr = request.getParameter("echostr");
		if(isCheck(request, token)) {
			try {
				PrintWriter out = response.getWriter();
				out.print(echostr);
				out.flush();
				out.close();
			} catch (Exception e) {
				log.error("", e);
			}
		}
	}
	
	/**
	 * 验证服务器地址(URL)
	 * @param request
	 * @param token		令牌(Token)
	 * @return
	 */
	public static boolean isCheck(HttpServletRequest request, String token) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		return SignUtil.checkSignature(token, signature, timestamp, nonce);
	}
	
	/**
	 * @Title: decryptMsg
	 * @Description: 微信服务器与应用服务器之间消息通信
	 * @author:zhangwei
	 * @date: Sep 20, 2019 1:30:38 PM
	 * @param: @param request
	 * @param: @param wc
	 * @param: @param ciphertext
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String decryptMsg(HttpServletRequest request, WxConfig wc, String ciphertext) {
		if (wc.getIssafe()) {
			String msgSignature = request.getParameter("msg_signature");
			String timeStamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			log.info("timeStamp:{},nonce:{},msgSignature:{},ciphertext:{}", timeStamp, nonce, msgSignature, ciphertext);
			return MsgEncryptUtil.decrypt(ciphertext, timeStamp, nonce, msgSignature, wc);
		} else {
			return ciphertext;
		}
	}
}
